package com.placement.app.interceptor;

import java.lang.reflect.Method;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.ThrowsAdvice;

import com.placement.app.util.Constants;


/**
 * Purpose: This class intercepts all request goes to Action class.
 * 
 * @author F020530
 *
 */
public class JobLogInterceptor implements MethodInterceptor,MethodBeforeAdvice, AfterReturningAdvice, ThrowsAdvice{
	private static final Log logger = LogFactory.getLog(JobLogInterceptor.class);

	public JobLogInterceptor(){
		logger.debug("constructor LolaLogInterceptor..");
	}
	  public Object invoke(MethodInvocation methodInvocation) throws Throwable
	  {
		  logger.debug("LolaLogInterceptor invoke method");
	    //logger.info("BEGIN: " + methodInvocation.getMethod().getDeclaringClass() + "::" + methodInvocation.getMethod().getName());
	    
	    long startTime = System.currentTimeMillis();
	    try
	    {
	      Object retVal = methodInvocation.proceed();
	      return retVal;
	    }catch(Exception e){
	    	logger.error(Constants.EVENT_TYPE_DIAGNOSIS + " "
					+ Constants.BUSINESS_PROCESS_NAME + " "
					+ this.getClass().getName() + " ",e);
	    	throw e;
	    }
	    finally
	    {
	      logger.info("TIME TAKEN: "  + methodInvocation.getMethod().getDeclaringClass() + "::" + methodInvocation.getMethod().getName()+"^"+(System.currentTimeMillis() - startTime)+" ms.");
	    }
	  }
	  
	  public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {			
		  logger.debug("LolaLogInterceptor before");
		  //logger.info("BEGIN: "+arg0.getDeclaringClass()+" "+arg0.getName()+" "+System.currentTimeMillis());
		  
		}
		
		public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable {		
			logger.debug("LolaLogInterceptor afterreturning");
			//logger.info("END: "+arg1.getDeclaringClass()+" "+arg1.getName()+" "+System.currentTimeMillis());		
		}
		
		public void afterThrowing(Method m, Object[] args, Object target, Throwable ex) 
		{ 
			//logger.info("EXCEPTION: "+ex.getStackTrace().toString()+" "+m.getDeclaringClass()+" "+m.getName()+" "+System.currentTimeMillis());	
		}

}
